﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CCF20Module.Properties;
using System.Web.Profile;
using CCF20Model;
using System.Text.RegularExpressions;
namespace CCF20Module
{
    /// <summary>
    /// Interaction logic for UserDetailsWindow.xaml
    /// </summary>
    public partial class UserDetailsWindow : Window
    {
        public UserDetailsWindow()
        {
            InitializeComponent();
        }

        internal MembershipUser DisplayedUser { get; set; }
        ProfileBase profile;
            
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (DisplayedUser != null)
            {
                lblUsername.Content = DisplayedUser.UserName;
                //txtEmailAddress.Text = DisplayedUser.Email;

                // TODO: manage all user properties

                String[] userRoles = Roles.GetRolesForUser(DisplayedUser.UserName);
                foreach (String r in userRoles)
                {
                    userRoleList.Items.Add(new ListViewItem()
                    {
                        Content = r
                    });
                }

                chkApproved.IsChecked = DisplayedUser.IsApproved;
                chkOnline.IsChecked = DisplayedUser.IsOnline;
                lblLastActivityDate.Content = DisplayedUser.LastActivityDate.ToShortDateString();
                //lblLastLockoutDate.Content = DisplayedUser.LastLockoutDate.ToShortDateString();
                lblLastLoginDate.Content = DisplayedUser.LastLoginDate.ToShortDateString();
                lblLastPasswordChangedDate.Content = DisplayedUser.LastPasswordChangedDate.ToShortDateString();
                lblCreationDate.Content = DisplayedUser.CreationDate.ToShortDateString();
                txtComment.Text = DisplayedUser.Comment;

                profile = ProfileBase.Create(DisplayedUser.UserName, true);
                txtMobile.Text = profile.GetPropertyValue("Mobile").ToString();
                txtIDSList.Text = profile.GetPropertyValue("IDS").ToString();
                if (!DisplayedUser.IsLockedOut)
                {
                    chkLockedOut.IsEnabled = false;
                }
            }
        }

        //private void btnOk_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        DisplayedUser.IsApproved = (chkApproved.IsChecked.HasValue && chkApproved.IsChecked.Value);
        //        DisplayedUser.Email = txtEmailAddress.Text;
        //        Membership.UpdateUser(DisplayedUser);
        //        this.Close();
        //    }
        //    catch (Exception ex)
        //    {
        //        Utility.ShowMessageBox(ex.Message);
        //    }
        //}

        //private void btnCancel_Click(object sender, RoutedEventArgs e)
        //{
        //    this.Close();
        //}

        private void btnDeleteRoles_Click(object sender, RoutedEventArgs e)
        {
            if (this.DisplayedUser != null)
            {
                Stack rolesToDelete = new Stack();
                String username = this.DisplayedUser.UserName;
                foreach (ListViewItem selectedItem in this.userRoleList.SelectedItems)
                {
                    String selectedRole = selectedItem.Content as String;
                    if (!String.IsNullOrEmpty(selectedRole))
                    {
                        if (Roles.IsUserInRole(username, selectedRole))
                        {
                            Roles.RemoveUserFromRole(username, selectedRole);
                            rolesToDelete.Push(selectedItem);
                        }
                    }
                }

                while (rolesToDelete.Count != 0)
                {
                    this.userRoleList.Items.Remove(rolesToDelete.Pop());
                }
            }
        }

        private void btnSelectRoles_Click(object sender, RoutedEventArgs e)
        {
            RolePickerDialogWindow dlg = new RolePickerDialogWindow();
            bool? dlgResult = dlg.ShowDialog();

            if (dlgResult.HasValue && dlgResult.Value)
            {
                String username = this.DisplayedUser.UserName;
                foreach (ListViewItem selectedItem in dlg.RoleListView.SelectedItems)
                {
                    String selectedRole = selectedItem.Content as String;
                    if (!String.IsNullOrEmpty(selectedRole))
                    {
                        if (!Roles.IsUserInRole(username, selectedRole))
                        {
                            Roles.AddUserToRole(username, selectedRole);
                            this.userRoleList.Items.Add(new ListViewItem()
                            {
                                Content = selectedRole
                            });
                        }
                    }
                }
            }
        }

        private void btnResetPassword_Click(object sender, RoutedEventArgs e)
        {
            UserResetPasswordDialogWindow dlg = new UserResetPasswordDialogWindow();
            if (DisplayedUser != null)
            {
                
                
                dlg.Title = String.Format(CultureInfo.CurrentUICulture, Properties.Resources.User_ResetPassword, this.DisplayedUser.UserName);
                bool? result = dlg.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    if (!string.IsNullOrEmpty(dlg.newPassword.Text) && 
                        !string.IsNullOrEmpty(dlg.newPasswordAgain.Text) &&
                        dlg.newPassword.Text == dlg.newPasswordAgain.Text)
                    {
                        bool success = DisplayedUser.ChangePassword(dlg.oldPassword.Text, dlg.newPassword.Text);
                        if (success)
                        {
                            Utility.ShowMessageBox(Properties.Resources.User_ResetPasswordSuccess);
                        }
                        else
                        {
                            Utility.ShowMessageBox(Properties.Resources.User_ResetPasswordFailure);
                        }
                    }
                    else
                    {
                        Utility.ShowMessageBox(Properties.Resources.User_ResetPasswordsDontMatch);
                    }
                }
            }
            if (dlg.IsActive)
            {
                dlg.Close();
                
            }
        }

        private void btnRetrievePassword_Click(object sender, RoutedEventArgs e)
        {
            DialogWindow dlg = new DialogWindow("获取密码提示框,请回答密码提示问题");
            try
            {
                
                dlg.SetDisplayValues(DisplayedUser.PasswordQuestion, String.Empty);
                bool? result = dlg.ShowDialog();

                if (result.HasValue && result.Value && !string.IsNullOrEmpty(dlg.textBox1.Text))
                {
                    String password = DisplayedUser.GetPassword(dlg.textBox1.Text);
                    Utility.ShowMessageBox(password);
                }

            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(ex.Message);
            }
            finally
            {
                dlg.Close();
            }
        }

        private void chkLockedOut_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (chkLockedOut.IsChecked.HasValue && chkLockedOut.IsChecked.Value == false)
                {
                    bool unlockResult = DisplayedUser.UnlockUser();
                    if (!unlockResult)
                    {
                        chkLockedOut.IsChecked = true;
                    }

                    String fmt = (unlockResult) ? Properties.Resources.User_UnlockSuccess : Properties.Resources.User_UnlockFail;
                    String msg = String.Format(CultureInfo.CurrentUICulture, fmt, DisplayedUser.UserName);
                    Utility.ShowMessageBox(msg);
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(ex.Message);
            }
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();   
        }

        private void btnProfile_Click(object sender, RoutedEventArgs e)
        {
            Regex regex = new Regex(@"^[0-9,]+$");
            if (!regex.Match(txtIDSList.Text.Trim()).Success)
            {
                Utility.ShowMessageBox("IDS 只可以是数字，用逗号隔开");
                return;
            }
            profile.SetPropertyValue("Mobile", txtMobile.Text.Trim());
            profile.SetPropertyValue("IDS", txtIDSList.Text.Trim());
            profile.Save();
            Utility.ShowMessageBox("保存成功");
        }

    }
}
